package com.heima.wemedia.service.impl;

import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.io.IOException;
import java.util.Date;

@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
    @Autowired
    private IScheduleClient scheduleClient;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 添加任务到延迟队列中
     *
     * @param id          文章的id
     * @param publishTime 发布的时间  可以做为任务的执行时间
     */
    @Override
    @Async
    public void addNewsToTask(Integer id, Date publishTime) {
        log.info("添加任务到延迟服务中...");
        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        task.setParameters(ProtostuffUtil.serialize(wmNews));

        scheduleClient.addTask(task);
        log.info("任务已添加到延迟服务");
    }

    /**
     * 扫描延迟队列中的任务，提交任务到 redis
     */
    @Override
    @Scheduled(fixedRate = 1000) // 每秒执行一次
//    @SneakyThrows // 忽略异常
    public void scanNewsByTask() throws TesseractException, IOException {
        // 1. 获取任务
        int taskType = TaskTypeEnum.NEWS_SCAN_TIME.getTaskType();
        int taskPriority = TaskTypeEnum.NEWS_SCAN_TIME.getPriority();
        int code = AppHttpCodeEnum.SUCCESS.getCode();
        ResponseResult<Task> poll = scheduleClient.poll(taskType, taskPriority);

        // 2. 判断是否有任务需要提交
        if (poll != null && poll.getCode() == code && poll.getData() != null) {
            Task task = poll.getData();
            WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);
            // 审核文章内容
            wmNewsAutoScanService.autoScanWmNewsAsync(wmNews.getId());
            log.info("消费并审核延迟任务：{}", task.getTaskId());
        }
    }
}
